package com.lqd.mall.system.service.impl;

import com.lqd.mall.basis.constant.SystemConstant;
import com.lqd.mall.basis.exception.ExceptionCast;
import com.lqd.mall.basis.utils.DateUtils;
import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.interaction.system.SysDeptEntity;
import com.lqd.mall.jpa.service.impl.BaseServiceImpl;
import com.lqd.mall.jpa.utils.DynamicSqlUtil;
import com.lqd.mall.security.utils.SecurityUtils;
import com.lqd.mall.system.repository.SysDeptRepository;
import com.lqd.mall.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 零起点
 * @create 2022-03-26 17:59
 */
@Service
public class SysDeptServiceImpl
        extends BaseServiceImpl<SysDeptRepository, SysDeptEntity, Long>
        implements ISysDeptService {

    @Resource
    SysDeptRepository sysDeptRepository;


    @Override
    public List<SysDeptEntity> listSysDeptEntity(SysDeptEntity entity) {
        if (entity == null) {
            entity = new SysDeptEntity();
        }
        entity.setDelFlag(SystemConstant.SYS_DEL_FLAG_EFFECTIVE);
        Example<SysDeptEntity> example = DynamicSqlUtil.setQueryConditions(entity);
        List<SysDeptEntity> entities = sysDeptRepository.findAll(example);
        return entities;
    }

    @Override
    public Integer save(SysDeptEntity entity) {

        if (entity == null || entity.getParentId() < 0) {
            ExceptionCast.cast("请选择父级");
        }
        if (StringUtils.isEmpty(entity.getDeptName())) {
            ExceptionCast.cast("请填入部门名称");
        }
        // 校验父级数据
        SysDeptEntity parent = sysDeptRepository.getOne(entity.getParentId());
        if (parent.getDeptId() == null) {
            ExceptionCast.cast("父级不存在");
        }
        SysDeptEntity q = new SysDeptEntity();
        q.setDelFlag(SystemConstant.SYS_DEL_FLAG_EFFECTIVE);
        q.setDeptName(entity.getDeptName());
        q.setParentId(parent.getDeptId());
        long count = sysDeptRepository.count(DynamicSqlUtil.setQueryConditions(q));
        if (count > 0) {
            ExceptionCast.cast("已存在");
        }
        // 添加数据
        String ancestors = parent.getAncestors();
        ancestors = ancestors + "," + parent.getDeptId();
        entity.setAncestors(ancestors);
        entity.setDelFlag(SystemConstant.SYS_DEL_FLAG_EFFECTIVE);
        entity.setCreateTime(new Date());
        entity.setCreateBy(SecurityUtils.getUsername());
        SysDeptEntity save = sysDeptRepository.save(entity);
        return 1;
    }

    @Override
    public Integer deleteSysDeptEntitById(Long deptId) {
        if (deptId < 0) {
            ExceptionCast.cast("部门id不正确");
        }
        SysDeptEntity entity = new SysDeptEntity();
        entity.setDeptId(deptId);
        entity.setDelFlag(SystemConstant.SYS_DEL_FLAG_DELETE);
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        Optional<Integer> integer = this.updateEntity(entity, "dept_id");
        return integer.get();
    }

    @Override
    public List<SysDeptEntity> excludeChild(Long deptId) {

        SysDeptEntity entity = new SysDeptEntity();
        entity.setDelFlag(SystemConstant.SYS_DEL_FLAG_EFFECTIVE);

        List<SysDeptEntity> list = sysDeptRepository.findAll(DynamicSqlUtil.setQueryConditions(entity));

        return list.stream().filter(item-> !(item.getDeptId().equals(deptId) ||
                ArrayUtils.contains(StringUtils.split(item.getAncestors(), ","), deptId + ""))
        ).collect(Collectors.toList());
    }

    @Override
    public Integer upateSysDeptEntity(SysDeptEntity entity) {
        SysDeptEntity deptEntity = sysDeptRepository.getOne(entity.getDeptId());

        if (deptEntity == null||deptEntity.getDeptId() == null) {
            ExceptionCast.cast("部门信息不存在");
        }
        // 添加数据
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        Optional<Integer> integer = this.updateEntity(entity, "dept_id");
        return integer.get();
    }

    @Override
    public List<SysDeptEntity> treeselect(SysDeptEntity entity) {
        List<SysDeptEntity> entities = this.listSysDeptEntity(entity);
        List<SysDeptEntity> entityList = departmentInformation(entities, 0L, null);
        return entityList;
    }

    private List<SysDeptEntity> departmentInformation(List<SysDeptEntity> entities, Long parentId, String parentName) {

        if (CollectionUtils.isEmpty(entities)) {
            return new ArrayList<>();
        }
        return entities.stream()
                .filter(parentNode -> parentNode.getParentId().equals(parentId))
                .map(node -> {
                    node.setChildren(departmentInformation(entities, node.getDeptId(), node.getDeptName()));
                    node.setParentName(parentName);
                    return node;
                }).collect(Collectors.toList());


    }


}
